package com.lyl.activiti.demo.web.controller;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.identity.User;
import org.activiti.engine.impl.interceptor.Command;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.repository.ProcessDefinitionQuery;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.lyl.activiti.demo.bean.BusinessInfo;
import com.lyl.activiti.demo.bean.BusinessInfoExample;
import com.lyl.activiti.demo.bean.BusinessInfoExample.Criteria;
import com.lyl.activiti.demo.bean.Leave;
import com.lyl.activiti.demo.bpm.cmd.HistoryProcessInstanceDiagramCmd;
import com.lyl.activiti.demo.bpm.cmd.WithdrawTaskCmd;
import com.lyl.activiti.demo.mapper.BusinessInfoMapper;
import com.lyl.activiti.demo.mapper.CustomMapper;
import com.lyl.activiti.demo.mapper.LeaveMapper;

/**
 * 
 * @author lijj
 * 
 */

@Controller
@RequestMapping(value = "/lc01test")
public class LC01TestController extends BaseController {

	@Autowired
	LeaveMapper leaveMapper;
	@Autowired
	CustomMapper customMapper;
	@Autowired
	BusinessInfoMapper businessInfoMapper;

	private static final String LC01_TEST_DEFINITION_KEY = "testLc";
	private static String IS_FIRST_IN="yes";
	private static String IS_FIRST_IN_FZ="yes";//manager--代表从经营业务经理到副总;planOfficerModify--代表从计划主管修改信息到副总;yes--代表第一次进入

	/**
	 * 流程列表
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/processList")
	public String processList(Model model) {
		ProcessDefinitionQuery processDefinitionQuery = repositoryService
				.createProcessDefinitionQuery();
		// 获取最新版本的流程定义
		List<ProcessDefinition> processDefinitionList = processDefinitionQuery
				.latestVersion().processDefinitionKey(LC01_TEST_DEFINITION_KEY)
				.orderByProcessDefinitionId().asc().list();

		model.addAttribute("processList", processDefinitionList);
		return "/lc01test/processList";
	}

	/**
	 * 保存流程业务信息
	 * 
	 * @param leave
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/saveBusinessInfo")
	public String saveBusinessInfo(BusinessInfo businessInfo,
			@RequestParam("id") String id, HttpSession session) {
		/*
		 * 启动用户信息 is_report_back=0表示审核通过的项目，is_report_back=1的项目表示审核退回的项目
		 */
		String userId = ((User) session.getAttribute("user")).getId();

		ProcessInstance processInstance = null;
		try {
			identityService.setAuthenticatedUserId(userId);
			// 启动流程同时存储变量map和businesskey
			processInstance = runtimeService
					.startProcessInstanceByKey(LC01_TEST_DEFINITION_KEY);
		} finally {
			identityService.setAuthenticatedUserId(null);
		}
		session.setAttribute("processInstanceId", processInstance.getId());

		Task task = taskService.createTaskQuery()
				.processInstanceId(processInstance.getId()).singleResult();

		taskService.complete(task.getId());
		return "redirect:/lc01test/toDoProcessList";
	}

	/**
	 * 开启流程
	 * 
	 * @param leave
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/startProcess")
	public String startProcess(HttpSession session) {
		return "redirect:/lc01test/getBusinessForm";
	}

	/**
	 * 获取业务信息
	 * 
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/getBusinessForm")
	public String getBusinessForm(Model model) {
		// 在此处需要做一些查询，查出验收 人，负责人的下拉框选项
		List<User> list = identityService.createUserQuery().list();
		model.addAttribute("userList", list);
		BusinessInfoExample businessInfoExample = new BusinessInfoExample();
		List<BusinessInfo> businessInfos = businessInfoMapper
				.selectByExample(businessInfoExample);
		model.addAttribute("businessInfos", businessInfos);
		return "/lc01test/startBusinessList";
	}

	/**
	 * 获取当前任务的表单
	 * 
	 * @param taskDefinitionKey
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getTaskForm/{taskDefinitionKey}/{taskId}/{processInstanceId}")
	public String getTaskForm(
			@PathVariable("taskDefinitionKey") String taskDefinitionKey,
			@PathVariable("taskId") String taskId,
			@PathVariable("processInstanceId") String processInstanceId,
			Model model) throws Exception {
		
		BusinessInfoExample businessInfoExample = new BusinessInfoExample();
		List<BusinessInfo> businessInfos = new ArrayList<BusinessInfo>();
//		List<BusinessInfo> businessInfos = businessInfoMapper
//				.selectByExample(businessInfoExample);
//		List<BusinessInfo> businessInfosReject = new ArrayList<BusinessInfo>();
//		List<BusinessInfo> businessInfosAgree = new ArrayList<BusinessInfo>();
//		for (BusinessInfo businessInfo : businessInfos) {
//			if (businessInfo.getRejectReason().equals("1")) {
//				businessInfosReject.add(businessInfo);
//			} else if (businessInfo.getRejectReason().equals("0")) {
//				businessInfosAgree.add(businessInfo);
//			}
//		}
		if ("planOfficer".equals(taskDefinitionKey)) {
			// 查询列表信息
			businessInfoExample = new BusinessInfoExample();
			Criteria criteria = businessInfoExample.createCriteria();
			criteria.andIsReportBackEqualTo(1);
			criteria.andRejectReasonEqualTo("1");
			businessInfos = businessInfoMapper
					.selectByExample(businessInfoExample);
			model.addAttribute("businessInfos", businessInfos);
			return "/lc01test/startBusinessList1";
		} else if ("businessManager".equals(taskDefinitionKey)) {
			businessInfoExample = new BusinessInfoExample();
			Criteria criteria = businessInfoExample.createCriteria();
			criteria.andIsReportBackEqualTo(0);
			//判断是否是第一次进入，如果不是第一次进入 ，则加入查询条件
			if(!IS_FIRST_IN.equals("yes")){
				criteria.andRejectReasonEqualTo("1");
			}
			businessInfos = businessInfoMapper
					.selectByExample(businessInfoExample);
			model.addAttribute("businessInfos", businessInfos);
			return "/lc01test/managerApprove";
		} else if ("viceManager".equals(taskDefinitionKey)) {
			businessInfoExample = new BusinessInfoExample();
			Criteria criteria = businessInfoExample.createCriteria();
			criteria.andIsReportBackEqualTo(0);
			//判断是否是第一次进入，如果不是第一次进入 ，则加入查询条件
			if(IS_FIRST_IN_FZ.equals("planOfficerModify")){
				criteria.andRejectReasonEqualTo("3");
			}else if(IS_FIRST_IN_FZ.equals("manager")){
				criteria.andRejectReasonEqualTo("2");
			}else{
				criteria.andRejectReasonEqualTo("1");
			}
			businessInfos = businessInfoMapper
					.selectByExample(businessInfoExample);
			model.addAttribute("businessInfos", businessInfos);
			return "/lc01test/viceManagerApprove";
		} else if ("planOfficerModify".equals(taskDefinitionKey)) {
			// 查询列表信息
			businessInfoExample = new BusinessInfoExample();
			Criteria criteria = businessInfoExample.createCriteria();
			criteria.andIsReportBackEqualTo(1);
			criteria.andRejectReasonEqualTo("3");
			businessInfos = businessInfoMapper
					.selectByExample(businessInfoExample);
			model.addAttribute("businessInfos", businessInfos);
			return "/lc01test/planOfficerModify";
		}
		return "";
	}

	@RequestMapping(value = "/getFinishedTaskForm/{businessKey}")
	public String getFinishedTaskForm(
			@PathVariable("businessKey") int businessKey, Model model) {
		Leave leave = leaveMapper.selectByPrimaryKey(businessKey);
		model.addAttribute("leave", leave);
		return "/lc01test/finishedTaskForm";
	}

	/**
	 * 完成经理审批
	 * 
	 * @param leave
	 * @param deptLeaderPass
	 * @param taskId
	 * @param session
	 * @return
	 */
	/*
	 * @RequestMapping(value = "/completeTaskManagerApprove")
	 * 
	 * @ResponseBody public String completeTaskManagerApprove(Leave leave,
	 * 
	 * @RequestParam("deptLeaderPass") String deptLeaderPass,
	 * 
	 * @RequestParam("taskId") String taskId, HttpSession session) { String
	 * userId = ((User) session.getAttribute("user")).getId(); // 更新leave表
	 * leaveMapper.updateByPrimaryKeySelective(leave);
	 * 
	 * Map<String, String> formProperties = new HashMap<String, String>();
	 * formProperties.put("deptLeaderPass", deptLeaderPass); try {
	 * identityService.setAuthenticatedUserId(userId);
	 * formService.submitTaskFormData(taskId, formProperties); } finally {
	 * identityService.setAuthenticatedUserId(null); } return "true"; }
	 */
	/**
	 * 完成经营业务经理审查
	 * 
	 * @param leave
	 * @param deptLeaderPass
	 * @param taskId
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/completeTaskManagerApprove")
	@ResponseBody
	public String completeTaskManagerApprove(
			@RequestParam("taskId") String taskId, HttpSession session) {
		String userId = ((User) session.getAttribute("user")).getId();
		//此处将IS_FIRST_IN置为false,说明不是第一次进入
//		IS_FIRST_IN="false";
		// 更新businessinfo表
		BusinessInfoExample businessInfoExample = new BusinessInfoExample();
		businessInfoExample = new BusinessInfoExample();
		Criteria criteria = businessInfoExample.createCriteria();
		criteria.andIsReportBackEqualTo(0);
		//判断是否是第一次进入，如果不是第一次进入 ，则加入查询条件
		if(!IS_FIRST_IN.equals("yes")){
			criteria.andRejectReasonEqualTo("1");
		}
		List<BusinessInfo> businessInfos = businessInfoMapper
				.selectByExample(businessInfoExample);
		

		Map<String, String> formProperties = new HashMap<String, String>();
		// 设置通过的项目往下走，未通过的项目往回走
		formProperties.put("managerPass", "pass");
		// 将前两条信息的is_report_back设为1，代表不同意的项目
		// 在这里暂时使用reject_reason=“0”代替是经营业务经理第一次进入，reject_reason=“1”是经营业务经理退回的时候进入
		if(businessInfos!=null && businessInfos.size()==2){
			BusinessInfo bInfo = businessInfos.get(0);
			bInfo.setIs_report_back(0);
			bInfo.setRejectReason("1");
			businessInfoMapper.updateByPrimaryKeySelective(bInfo);
			bInfo = businessInfos.get(1);
			bInfo.setIs_report_back(0);
			bInfo.setRejectReason("1");
			businessInfoMapper.updateByPrimaryKeySelective(bInfo);
			formProperties.put("managerUnPass", "unpass");//此处说明审核通过
		}else if(businessInfos.size()>2){
			BusinessInfo bInfo = businessInfos.get(0);
			bInfo.setIs_report_back(1);
			bInfo.setRejectReason("1");
			businessInfoMapper.updateByPrimaryKeySelective(bInfo);
			bInfo = businessInfos.get(1);
			bInfo.setIs_report_back(1);
			bInfo.setRejectReason("1");
			bInfo = businessInfos.get(2);
			bInfo.setRejectReason("2");//设置为2，说明是已经通过经营业务经理审核的项目
			businessInfoMapper.updateByPrimaryKeySelective(bInfo);
			bInfo = businessInfos.get(3);
			bInfo.setRejectReason("2");
			bInfo = businessInfos.get(4);
			bInfo.setRejectReason("2");
			businessInfoMapper.updateByPrimaryKeySelective(bInfo);
			formProperties.put("managerUnPass", "pass");
		}else{
			formProperties.put("managerUnPass", "pass");
		}
		
		try {
			identityService.setAuthenticatedUserId(userId);
			formService.submitTaskFormData(taskId, formProperties);
		} finally {
			identityService.setAuthenticatedUserId(null);
		}
		//此处将IS_FIRST_IN置为false,说明不是第一次进入
		IS_FIRST_IN="false";
		return "true";
	}

	/**
	 * 完成计划主管修改业务信息
	 */
	@RequestMapping(value = "/completeTaskPlanOfficer")
	@ResponseBody
	public String completeTaskPlanOfficer(
			@RequestParam("taskId") String taskId, HttpSession session) {
		String userId = ((User) session.getAttribute("user")).getId();
		// 更新businessinfo表
		BusinessInfoExample businessInfoExample = new BusinessInfoExample();
		Criteria criteria = businessInfoExample.createCriteria();
		criteria.andIsReportBackEqualTo(1);
		criteria.andRejectReasonEqualTo("1");
		List<BusinessInfo> businessInfos = businessInfoMapper
				.selectByExample(businessInfoExample);
		// 将is_report_back设为0，代表同意的项目
		// 在这里暂时使用reject_reason=“0”（经营业务经理节点）代表是经营业务经理第一次进入，reject_reason=“1”代表的是由经营业务经理退回给计划主管的项目
		// 在这里暂时使用reject_reason=“2”（计划主管节点）代表是计划主管接收由科技业务经理退回的项目，reject_reason=“3”（计划主管修改业务信息 节点）代表的是计划主管修改由经营副总退回的业务信息
		for (BusinessInfo businessInfo : businessInfos) {
			businessInfo.setIs_report_back(0);
			businessInfoMapper.updateByPrimaryKeySelective(businessInfo);
		}
		try {
			identityService.setAuthenticatedUserId(userId);
			taskService.complete(taskId);
		} finally {
			identityService.setAuthenticatedUserId(null);
		}
		//此处将IS_FIRST_IN置为false,说明是从planOfficer处进入manager处
		IS_FIRST_IN="false";
		return "true";
	}
	/**
	 * 完成计划主管修改业务信息
	 */
	@RequestMapping(value = "/completeTaskPlanOfficerModify")
	@ResponseBody
	public String completeTaskPlanOfficerModify(
			@RequestParam("taskId") String taskId, HttpSession session) {
		String userId = ((User) session.getAttribute("user")).getId();
		
		// 更新businessinfo表
		BusinessInfoExample businessInfoExample = new BusinessInfoExample();
		Criteria criteria = businessInfoExample.createCriteria();
		criteria.andIsReportBackEqualTo(1);
		criteria.andRejectReasonEqualTo("3");
		List<BusinessInfo> businessInfos = businessInfoMapper
				.selectByExample(businessInfoExample);
		// 将is_report_back设为0，代表同意的项目
		// 在这里暂时使用reject_reason=“0”代表是经营业务经理第一次进入，reject_reason=“1”是经营业务经理退回的时候进入
		// 在这里暂时使用reject_reason=“2”代表是计划主管接收由科技业务经理退回的项目，reject_reason=“3”代表的是由经营副总退回给计划主管的项目
		for (BusinessInfo businessInfo : businessInfos) {
			businessInfo.setIs_report_back(0);
			businessInfo.setRejectReason("3");
			businessInfoMapper.updateByPrimaryKeySelective(businessInfo);
		}
		
		try {
			identityService.setAuthenticatedUserId(userId);
			taskService.complete(taskId);
		} finally {
			identityService.setAuthenticatedUserId(null);
		}
		//此处将IS_FIRST_IN置为planOfficerModify,说明是从planOfficerModify处进入副总
		IS_FIRST_IN_FZ="planOfficerModify";
		return "true";
	}

	// @RequestMapping(value = "/completeTaskViceManagerApprove")
	// @ResponseBody
	// public String completeTaskViceManagerApprove(
	// @RequestParam("taskId") String taskId, HttpSession session) {
	// System.out.println("test");
	// return "true";
	// }

	/**
	 * 完成经营副总审批
	 * 
	 * @param businessInfo
	 * @param deptLeaderPass
	 * @param taskId
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/completeTaskViceManagerApprove")
	@ResponseBody
	public String completeTaskViceManagerApprove(
			@RequestParam("taskId") String taskId,
			HttpSession session) {
		String userId = ((User) session.getAttribute("user")).getId();
		
		
		BusinessInfoExample businessInfoExample = new BusinessInfoExample();
		businessInfoExample = new BusinessInfoExample();
		Criteria criteria = businessInfoExample.createCriteria();
		criteria.andIsReportBackEqualTo(0);
		//判断是否是第一次进入，如果不是第一次进入 ，则加入查询条件
		if(IS_FIRST_IN_FZ.equals("manager")){
			criteria.andRejectReasonEqualTo("2");
		}else if(IS_FIRST_IN_FZ.equals("planOfficerModify")){
			criteria.andRejectReasonEqualTo("3");
		}else{
			criteria.andRejectReasonEqualTo("1");
		}
		List<BusinessInfo> businessInfos = businessInfoMapper
				.selectByExample(businessInfoExample);
		// 将前两条信息的is_report_back设为1，代表不同意的项目
		// 在这里暂时使用reject_reason=“0”代替是经营业务经理第一次进入，reject_reason=“1”是经营业务经理退回的时候进入
		
		
		Map<String, String> formProperties = new HashMap<String, String>();
		
		if(businessInfos!=null && businessInfos.size()==2){
			BusinessInfo bInfo = businessInfos.get(0);
			bInfo.setIs_report_back(0);
			bInfo.setRejectReason("4");//说明经营副总审核通过
			businessInfoMapper.updateByPrimaryKeySelective(bInfo);
			bInfo = businessInfos.get(1);
			bInfo.setIs_report_back(0);
			bInfo.setRejectReason("4");
			businessInfoMapper.updateByPrimaryKeySelective(bInfo);
			formProperties.put("fuzhongUnPass", "unpass");
			formProperties.put("fuzhongPass", "end");// 同时需用代码开启另一段流程;
		}else if(businessInfos.size()>2){
			BusinessInfo bInfo = businessInfos.get(0);
			bInfo.setIs_report_back(1);
			bInfo.setRejectReason("3");
			businessInfoMapper.updateByPrimaryKeySelective(bInfo);
			bInfo = businessInfos.get(1);
			bInfo.setIs_report_back(1);
			bInfo.setRejectReason("3");
			businessInfoMapper.updateByPrimaryKeySelective(bInfo);
			bInfo = businessInfos.get(2);
			bInfo.setIs_report_back(0);
			bInfo.setRejectReason("4");
			businessInfoMapper.updateByPrimaryKeySelective(bInfo);
			formProperties.put("fuzhongUnPass", "pass");
			formProperties.put("fuzhongPass", "end");
		}else{
			formProperties.put("fuzhongUnPass", "pass");
			formProperties.put("fuzhongPass", "end");// 同时需用代码开启另一段流程
		}
		
		try {
			identityService.setAuthenticatedUserId(userId);
			formService.submitTaskFormData(taskId, formProperties);
		} finally {
			identityService.setAuthenticatedUserId(null);
		}
		//此处将IS_FIRST_IN置为manager,说明是从manager处进入副总
		IS_FIRST_IN_FZ="manager";
		return "true";
	}

	/**
	 * 完成修改申请
	 * 
	 * @param leave
	 * @param reApply
	 * @param taskId
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/completeTaskModifyApply")
	public String completeTaskModifyApply(Leave leave,
			@RequestParam("reApply") String reApply,
			@RequestParam("taskId") String taskId, HttpSession session) {
		String userId = ((User) session.getAttribute("user")).getId();
		// 更新leave表
		leaveMapper.updateByPrimaryKeySelective(leave);

		Map<String, String> formProperties = new HashMap<String, String>();
		formProperties.put("reApply", reApply);
		try {
			identityService.setAuthenticatedUserId(userId);
			formService.submitTaskFormData(taskId, formProperties);
		} finally {
			identityService.setAuthenticatedUserId(null);
		}
		return "/lc01test/processList";
	}

	/**
	 * 销假
	 * 
	 * @param taskId
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/completeTaskReportBack")
	public String completeTaskReportBack(@RequestParam("taskId") String taskId,
			HttpSession session) {
		String userId = ((User) session.getAttribute("user")).getId();
		try {
			identityService.setAuthenticatedUserId(userId);
			taskService.complete(taskId);
		} finally {
			identityService.setAuthenticatedUserId(null);
		}
		return "/lc01test/processList";
	}

	/**
	 * 待办任务列表
	 * 
	 * @param model
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/toDoProcessList")
	public String userToDoProcessList(Model model, HttpSession session) {
		String userId = ((User) session.getAttribute("user")).getId();
		// 获取当前用户为候选人的任务
		List<Task> tasks = taskService.createTaskQuery()
				.processDefinitionKey(LC01_TEST_DEFINITION_KEY)
				.taskCandidateUser(userId).list();
		// 获取已经分配给当前用户的任务
		List<Task> tasks1 = taskService.createTaskQuery()
				.processDefinitionKey(LC01_TEST_DEFINITION_KEY)
				.taskAssignee(userId).list();
		tasks.addAll(tasks1);
		model.addAttribute("tasks", tasks);

		// 根据待办中的processInstanceId获得ProcessInstance ProcessDefinition
		HashMap<String, HistoricProcessInstance> historicProcessInstances = new HashMap<String, HistoricProcessInstance>();
		HashMap<String, ProcessDefinition> processDefinitions = new HashMap<String, ProcessDefinition>();
		for (Task task : tasks) {
			HistoricProcessInstance historicProcessInstance = historyService
					.createHistoricProcessInstanceQuery()
					.processInstanceId(task.getProcessInstanceId())
					.singleResult();
			historicProcessInstances.put(task.getProcessInstanceId(),
					historicProcessInstance);

			ProcessDefinition processDefinition = repositoryService
					.createProcessDefinitionQuery()
					.processDefinitionId(task.getProcessDefinitionId())
					.singleResult();
			processDefinitions.put(task.getProcessDefinitionId(),
					processDefinition);
		}
		model.addAttribute("historicProcessInstances", historicProcessInstances);
		model.addAttribute("processDefinitions", processDefinitions);

		return "/lc01test/toDoProcessList";
	}

	/**
	 * 已退回的任务列表
	 * 
	 * @param model
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/reportBackProcessList")
	public String userReportBackProcessList(Model model, HttpSession session) {
		String userId = ((User) session.getAttribute("user")).getId();

		// model.addAttribute("businessInfo", businessInfo);
		// 此处为测试
		// 获取已经分配给当前用户的任务
		List<Task> tasks = new ArrayList<Task>();
		BusinessInfoExample example = new BusinessInfoExample();
		List<BusinessInfo> busList = businessInfoMapper
				.selectByExample(example);
		for (BusinessInfo info : busList) {
			if (info.getIs_report_back() == 1) {
				Integer buskey = info.getId();
				HistoricProcessInstance historicProcessInstance = historyService
						.createHistoricProcessInstanceQuery()
						.processInstanceBusinessKey(String.valueOf(buskey))
						.singleResult();
				String processId = historicProcessInstance.getId();
				List<Task> temp = taskService.createTaskQuery()
						.taskAssignee(userId).processInstanceId(processId)
						.list();
				List<Task> temp2 = taskService.createTaskQuery()
						.taskCandidateUser(userId).processInstanceId(processId)
						.list();
				tasks.addAll(temp);
				tasks.addAll(temp2);
			}
		}

		model.addAttribute("tasks", tasks);

		// 根据待办中的processInstanceId获得ProcessInstance ProcessDefinition
		HashMap<String, HistoricProcessInstance> historicProcessInstances = new HashMap<String, HistoricProcessInstance>();
		HashMap<String, ProcessDefinition> processDefinitions = new HashMap<String, ProcessDefinition>();
		for (Task task : tasks) {
			HistoricProcessInstance historicProcessInstance = historyService
					.createHistoricProcessInstanceQuery()
					.processInstanceId(task.getProcessInstanceId())
					.singleResult();
			historicProcessInstances.put(task.getProcessInstanceId(),
					historicProcessInstance);

			ProcessDefinition processDefinition = repositoryService
					.createProcessDefinitionQuery()
					.processDefinitionId(task.getProcessDefinitionId())
					.singleResult();
			processDefinitions.put(task.getProcessDefinitionId(),
					processDefinition);
		}
		model.addAttribute("historicProcessInstances", historicProcessInstances);
		model.addAttribute("processDefinitions", processDefinitions);

		return "/lc01test/toDoProcessList";
	}

	/**
	 * 签收流程
	 * 
	 * @param taskId
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/claimProcess")
	public String claimProcess(String taskId, HttpSession session) {
		String userId = ((User) session.getAttribute("user")).getId();
		taskService.claim(taskId, userId);
		return "redirect:/lc01test/toDoProcessList";
	}

	/**
	 * 运行中流程
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/runningProcessList")
	public String runningProcess(Model model, HttpSession session) {
		String userId = ((User) session.getAttribute("user")).getId();
		List<ProcessInstance> runningProcessList = runtimeService
				.createProcessInstanceQuery()
				.processDefinitionKey(LC01_TEST_DEFINITION_KEY)
				.involvedUser(userId).active().list();
		model.addAttribute("runningProcessList", runningProcessList);

		// 根据processDefinitionId获得 ProcessDefinition
		HashMap<String, ProcessDefinition> processDefinitions = new HashMap<String, ProcessDefinition>();
		for (ProcessInstance processInstance : runningProcessList) {
			ProcessDefinition processDefinition = repositoryService
					.createProcessDefinitionQuery()
					.processDefinitionId(
							processInstance.getProcessDefinitionId())
					.singleResult();
			processDefinitions.put(processInstance.getProcessDefinitionId(),
					processDefinition);
		}
		model.addAttribute("processDefinitions", processDefinitions);
		return "/lc01test/runningProcessList";
	}

	/**
	 * 显示流程的详细历史
	 * 
	 * @param processInstanceId
	 * @param model
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/runningProcessHistory/{processInstanceId}")
	public String runningProcessHistory(
			@PathVariable("processInstanceId") String processInstanceId,
			Model model, HttpSession session) {
		String userId = ((User) session.getAttribute("user")).getId();

		List<HistoricTaskInstance> historicTasks = historyService
				.createHistoricTaskInstanceQuery()
				.processInstanceId(processInstanceId).list();
		model.addAttribute("historicTasks", historicTasks);

		return "/lc01test/processHistory";
	}

	/**
	 * 已完成的流程实例
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/finishedProcessList")
	public String finished(Model model, HttpServletRequest request,
			HttpSession session) {
		String userId = ((User) session.getAttribute("user")).getId();
		List<HistoricProcessInstance> finishedProcessList = historyService
				.createHistoricProcessInstanceQuery()
				.processDefinitionKey(LC01_TEST_DEFINITION_KEY)
				.startedBy(userId).orderByProcessInstanceEndTime().desc()
				.finished().list();
		model.addAttribute("finishedProcessList", finishedProcessList);

		// 根据processDefinitionId获得 ProcessDefinition
		HashMap<String, ProcessDefinition> processDefinitions = new HashMap<String, ProcessDefinition>();
		for (HistoricProcessInstance historicProcessInstance : finishedProcessList) {
			ProcessDefinition processDefinition = repositoryService
					.createProcessDefinitionQuery()
					.processDefinitionId(
							historicProcessInstance.getProcessDefinitionId())
					.singleResult();
			processDefinitions.put(
					historicProcessInstance.getProcessDefinitionId(),
					processDefinition);
		}
		model.addAttribute("processDefinitions", processDefinitions);
		return "/lc01test/finishedProcessList";
	}

	/**
	 * 获取当前流程实例的流程图
	 * 
	 * @param processInstanceId
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "/image/{processInstanceId}")
	public void getImage(
			@PathVariable("processInstanceId") String processInstanceId,
			HttpServletResponse response) throws Exception {
		Command<InputStream> cmd = new HistoryProcessInstanceDiagramCmd(
				processInstanceId);

		InputStream is = managementService.executeCommand(cmd);
		response.setContentType("image/png");

		int len = 0;
		byte[] b = new byte[1024];

		while ((len = is.read(b, 0, 1024)) != -1) {
			response.getOutputStream().write(b, 0, len);
		}
	}

	/**
	 * 获取流程定义图
	 * 
	 * @param processDefinitionId
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "/processDefinitionImage/{processDefinitionId}")
	public void getProcessDefinitionImage(
			@PathVariable("processDefinitionId") String processDefinitionId,
			HttpServletResponse response) throws Exception {
		ProcessDefinition processDefinition = repositoryService
				.createProcessDefinitionQuery()
				.processDefinitionId(processDefinitionId).singleResult();
		InputStream resourceAsStream = repositoryService.getResourceAsStream(
				processDefinition.getDeploymentId(),
				processDefinition.getDiagramResourceName());
		byte[] b = new byte[1024];
		int len = -1;
		while ((len = resourceAsStream.read(b, 0, 1024)) != -1) {
			response.getOutputStream().write(b, 0, len);
		}
	}

	/**
	 * 已办任务
	 * 
	 * @param model
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/processedTaskList")
	public String processedTaskList(Model model, HttpSession session) {
		String userId = ((User) session.getAttribute("user")).getId();
		List<HistoricTaskInstance> processedTasks = historyService
				.createHistoricTaskInstanceQuery()
				.processDefinitionKey(LC01_TEST_DEFINITION_KEY)
				.taskAssignee(userId).finished().list();
		model.addAttribute("processedTasks", processedTasks);
		// 根据processInstanceId获得processInstace
		HashMap<String, HistoricProcessInstance> processInstances = new HashMap<String, HistoricProcessInstance>();
		for (HistoricTaskInstance processedTask : processedTasks) {
			HistoricProcessInstance historicProcessInstance = historyService
					.createHistoricProcessInstanceQuery()
					.processInstanceId(processedTask.getProcessInstanceId())
					.singleResult();
			processInstances.put(processedTask.getProcessInstanceId(),
					historicProcessInstance);
		}
		model.addAttribute("processInstances", processInstances);
		return "/lc01test/processedTaskList";
	}

	/**
	 * 撤销已办任务
	 * 
	 * @param taskId
	 * @return
	 */
	@RequestMapping(value = "/callBack/{taskId}")
	@ResponseBody
	public String callBack(@PathVariable("taskId") String taskId) {
		Command<Integer> cmd = new WithdrawTaskCmd(taskId);
		return managementService.executeCommand(cmd).toString();
	}

}
